package service

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gogf/gf/v2/util/guid"
	"os/exec"
	"strings"
	"wx_build/core/msg"
	"wx_build/global"
	"wx_build/model/tables"
	"wx_build/utils"
)

type ProjectService struct {
	tables.Project
	Page   int    `json:"page"`
	Size   int    `json:"size"`
	Search string `json:"search"`
}

func (c *ProjectService) Add(g *gin.Context) {
	c.ProjectId = guid.S()
	query := tables.Project{
		ProjectName: c.ProjectName,
	}
	err := query.QueryOne(&query)
	if err == nil {
		msg.Error(g, "项目已存在", err)
		return
	}
	err = c.Project.Add(&c.Project)
	if err != nil {
		msg.Error(g, "添加项目失败", err)
		return
	}
	msg.Success(g, "添加项目成功")
	return
}
func (c *ProjectService) Update(g *gin.Context) {
	query := tables.Project{
		ProjectId: c.ProjectId,
	}
	err := query.QueryOne(&query)
	if err != nil {
		msg.Error(g, "项目不存在", err)
		return
	}
	query.ProjectName = c.ProjectName
	query.GitUrl = c.GitUrl
	query.Branch = c.Branch
	query.DeploymentWay = c.DeploymentWay
	query.Token = c.Token
	query.Appid = c.Appid
	query.GitUser = c.GitUser
	query.GitPassword = c.GitPassword
	query.CompileCommand = c.CompileCommand
	query.BuildPath = c.BuildPath
	query.PerformBefore = c.PerformBefore
	db := global.Sqlite
	err = db.Save(&query).Error
	if err != nil {
		msg.Error(g, "编辑项目失败", err)
		return
	}
	msg.Success(g, "编辑项目成功")
	return

}
func (c *ProjectService) List(g *gin.Context) {
	list := new([]tables.Project)
	var count int64
	db := global.Sqlite
	if c.Search != "" {
		db = db.Where("project_name LIKE ?", "%"+c.Search+"%")
	}
	db.Where(c.Project).Find(&list).Count(&count)
	db.Where(c.Project).Order("created_at desc").Limit(c.Size).Offset((c.Page - 1) * c.Size).Find(&list)
	data := make([]map[string]interface{}, len(*list))
	for k, v := range *list {
		item, _ := utils.ToMap(v)
		item["app_info"] = c.getAppInfo(v.Appid)
		data[k] = item
	}
	res := make(map[string]interface{})
	res["count"] = count
	res["list"] = data
	msg.Success(g, "查询列表成功", res)
	return
}
func (c *ProjectService) getAppInfo(appid string) map[string]interface{} {
	app := tables.WxApplet{
		Appid: appid,
	}
	app.QueryOne(&app)
	res, _ := utils.ToMap(app)
	return res
}
func (c *ProjectService) Delete(g *gin.Context) {
	query := tables.Project{
		ProjectId: c.ProjectId,
	}
	err := query.QueryOne(&query)
	if err != nil {
		msg.Error(g, "项目不存在", err)
		return
	}
	db := global.Sqlite
	err = db.Delete(&query).Error
	if err != nil {
		msg.Error(g, "删除项目失败", err)
		return
	}
	msg.Success(g, "删除项目成功")
	return
}
func (c *ProjectService) GetBranchList(g *gin.Context) {
	url := getGitUrl(c.GitUrl, c.GitUser, c.GitPassword)
	option := []string{
		"ls-remote",
		"--heads",
		"--tags",
		url,
	}
	cmd := exec.Command("git", option...)
	out, err := cmd.CombinedOutput()
	if err != nil {
		msg.Error(g, "查询分支列表失败", err)
		return
	}
	var branchList []string
	list := strings.Split(string(out), "\n")
	for _, v := range list {
		//fmt.Println("item:", v)
		itemList := strings.Split(v, "\t")
		if len(itemList) > 1 {
			branch := strings.ReplaceAll(itemList[1], "refs/heads/", "")
			if branch != "" {
				branchList = append(branchList, branch)
			}
		}
	}
	msg.Success(g, "查询成功", branchList)
	return
}

// 提取git url后缀
func getGitUrl(giturl, gituser, pwd string) string {
	if n := strings.Index(giturl, "http://"); n > -1 {
		url := strings.Replace(giturl, "http://", "", 1)
		user := strings.ReplaceAll(gituser, "@", "%40")
		password := strings.ReplaceAll(pwd, "@", "%40")
		return fmt.Sprintf("http://%s:%s@%s", user, password, url)
	} else {
		url := strings.Replace(giturl, "https://", "", 1)
		user := strings.ReplaceAll(gituser, "@", "%40")
		password := strings.ReplaceAll(pwd, "@", "%40")
		return fmt.Sprintf("https://%s:%s@%s", user, password, url)
	}
	return ""
}
func (c *ProjectService) ProjectBuild(g *gin.Context) {
	project := tables.Project{
		ProjectId: c.ProjectId,
	}
	task := tables.Task{
		TaskId:    guid.S(),
		ProjectId: c.ProjectId,
		Type:      project.DeploymentWay,
		Status:    "待运行",
	}
	err := task.Add(&task)
	if err != nil {
		msg.Error(g, "发B起构建失败", err)
		return
	}
	msg.Success(g, "发起构建成功")
	return
}
